package com.waypolice.common.utils;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.commons.codec.binary.Base64;
/**
 * 
 * @ClassName: DESUtil
 * @Description: DES加密解密方法
 * @author 宗义朋
 * @version 创建时间：2017-12-25 下午6:23:02
 *
 */
public class DESUtil {

	/**
	 * 加密功能
	 * @param datasource 需要加密的自己数组
	 * @param password 密钥
	 * @return
	 */
	public static String encrypt(byte[] datasource, String password) {
		try {
			Base64 b64 = new Base64();
			SecureRandom random = new SecureRandom();
			DESKeySpec desKey = new DESKeySpec(password.getBytes());
			// 创建一个密匙工厂，然后用它把DESKeySpec转换成
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey securekey = keyFactory.generateSecret(desKey);
			// Cipher对象实际完成加密操作
			Cipher cipher = Cipher.getInstance("DES");
			// 用密匙初始化Cipher对象
			cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
			// 现在，获取数据并加密
			// 正式执行加密操作
			byte[] encryptByte = cipher.doFinal(datasource);
			String encryptStr = new String(b64.encode(encryptByte));
			return encryptStr;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 解密功能
	 * @param src 需要解密的自己数组
	 * @param password 密钥
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(byte[] src, String password) {
		try {
			Base64 b64 = new Base64();
			byte[] decrypt = b64.decode(src);
			// DES算法要求有一个可信任的随机数源
			SecureRandom random = new SecureRandom();
			// 创建一个DESKeySpec对象
			DESKeySpec desKey;
			desKey = new DESKeySpec(password.getBytes());
			// 创建一个密匙工厂
			SecretKeyFactory keyFactory;
			keyFactory = SecretKeyFactory.getInstance("DES");
			// 将DESKeySpec对象转换成SecretKey对象
			SecretKey securekey = keyFactory.generateSecret(desKey);
			// Cipher对象实际完成解密操作
			Cipher cipher = Cipher.getInstance("DES");
			// 用密匙初始化Cipher对象
			cipher.init(Cipher.DECRYPT_MODE, securekey, random);
			// 真正开始解密操作
			byte[] decryptByte = cipher.doFinal(decrypt);
			return new String(decryptByte);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
